const finance = require('../../../utils/finance')
const { bindMpUser } = require('../../../utils/miniapp')
const app = getApp()

Page({
    data: {
      balance: 0,
      budgetSurplus: null, // 预算结余金额
      recordList: [],
      loading: false,
      pageSize: 25,
      // 目标列表
      goalTextList: [],
      // 是否隐藏金额
      isAmountHidden: false,
      // 是否刷新
      refreshing: false,
      // 账户相关
      accountList: [],
      accountIndex: -1,
      // 页面初始化状态
      isInitialized: false,
      showAccountSelector: false,
      // 防止重复请求的标志
      isRequesting: false,
    },
    async onLoad(options) {
      // 检查是否有 user 参数，如果有就调用 bindMpUser
      const mpOpenid = app.globalMpOpenid || (options && options.type === 'bind' && options.mpOpenid ? options.mpOpenid : '');
      if (mpOpenid) {
        console.log('options=', options)
        console.log('mpOpenid=', mpOpenid)
        app.globalMpOpenid = mpOpenid;
        // 获取小程序openid
        const openid = wx.getStorageSync('openid');
        if (!openid) {
          wx.showToast({
            title: '请先登录后再绑定公众号用户',
            icon: 'none'
          });
        } else {
          // 绑定公众号用户
          await this.toBindMpUser(openid, mpOpenid);
        }
      }
      
      // 防止重复初始化的标志
      let hasInitialized = false;
      
      // 账户就绪后再次初始化数据，解决未登录时首次进入空数据问题
      if (app && typeof app.onAccountReady === 'function') {
        app.onAccountReady(async () => {
          console.log('账户就绪后再次初始化数据')
          if (!hasInitialized) {
            hasInitialized = true;
            await this.initLoadAllData();
          }
        });
      }
      
      // 初始化数据（仅在首次加载时执行）
      if (!hasInitialized) {
        hasInitialized = true;
        await this.initLoadAllData();
      }
      
      this.setData({ isInitialized: true});
    },

    /**
     * 绑定公众号用户
     * @param {*} openid 
     * @param {*} mpOpenid 
     */
    async toBindMpUser(openid, mpOpenid) {
      try {
        await bindMpUser(openid, mpOpenid);
        console.log('绑定公众号用户成功');
        // 清空全局公众号openid参数
        app.globalMpOpenid = '';
      } catch (error) {
        console.error('绑定公众号用户失败:', error);
        wx.showToast({
          title: '绑定用户失败',
          icon: 'none'
        });
      }
    },
    // 加载所有数据(判断账户是否存在->加载初始化参数->加载记录)
    async initLoadAllData() {
      // 防止重复请求
      if (this.data.isRequesting) {
        console.log('请求进行中，跳过重复调用');
        return;
      }
      
      this.setData({ isRequesting: true });
      
      try {
        const { accountList, accountIndex } = await app.getAccountGlobal();
        if (accountList && accountList.length > 0) {
          this.setData({ accountList, accountIndex });
          // 加载数据
          await this.loadInitAndRecords();
        }
      } catch (e) {
        console.error('初始化数据失败:', e);
      } finally {
        this.setData({ isRequesting: false });
      }
    },
    async onAccountChange(e) {
      const idx = e.detail.value;
      this.setData({
        accountIndex: idx
      });
      // 设置全局账户索引
      app.setAccountIdxGlobal(idx);
      await this.initLoadAllData();
    },
    clickShowAccountSelector() {
      this.setData({ showAccountSelector: true });
    },
    async onSelectAccount(e) {
      const idx = e.detail.index;
      // 复用原有onAccountChange逻辑
      await this.onAccountChange({ detail: { value: idx } });
    },
    /**
     * 获取初始化参数 和 记录列表
     */
    async loadInitAndRecords() {
      try {
        const account = this.data.accountList[this.data.accountIndex];
        if (!account) {
          wx.showToast({ title:  '账户数据异常', icon: 'none' });
          return;
        }
        const res = await finance.indexInitParam({ accountBookId: account.id });
        if (res) {
          const goalTextList = Array.isArray(res.goalTextList) && res.goalTextList.length > 0? res.goalTextList: [];
          const thisMonthSurplus = res.thisMonthSurplus;
          const budgetSurplus = res.budgetSurplus; // 获取预算结余
          this.setData({
            goalTextList,
            balance: thisMonthSurplus,
            budgetSurplus: budgetSurplus // 设置预算结余
          });
          // 加载记录列表
          this.loadRecords();
        }
      } catch (e) {
        wx.showToast({ title:  (e && e.data && e.data.msg) || '获取初始化参数', icon: 'none' });
      }
    },
    async onShow() {
      // 只有在页面已经初始化后才执行刷新，避免重复初始化
      if (this.data.isInitialized && !this.data.isRequesting) {
        await this.initLoadAllData();
      }
    },
    /**
     * 下拉刷新
     */
    async onPullDownRefresh() {
      // 如果正在请求中，直接结束刷新
      if (this.data.isRequesting) {
        wx.stopPullDownRefresh();
        return;
      }
      
      this.setData({ refreshing: true });
      await this.initLoadAllData();
      wx.stopPullDownRefresh(); // 结束动画
      this.setData({ refreshing: false });
    },
    /**
     * 加载最近的记录
     * @returns 
     */
    async loadRecords() {
      if (this.data.loading) return;
      this.setData({ loading: true });
      try {
        const res = await finance.getTopFinanceRecordList({number: this.data.pageSize, accountBookId: this.data.accountList[this.data.accountIndex].id});
        if (!res || !Array.isArray(res)) {
          // 获取不到数据， 显示空数据效果
          this.setData({
            recordList: [],
            loading: false,
            page: 1
          });
          return;
        }
        // 假设res.data为数组
        const recordList = (res || []).map(item => ({
          id: item.id || item.accountBookId, // 若无id则用accountBookId
          type: item.financeType, // 'expense' or 'income'
          category: item.categoryName,
          categoryCode: item.categoryCode,
          financeDesc: item.financeDesc || '',
          amount: item.totalAmount,
          paymentMethod: item.paymentMethod,
          financeDate: item.financeDate,
          financeTime: item.financeTime,
          details: [],
          expanded: false,
          userName: item.userName
        }));
        this.setData({
          recordList,
          loading: false,
          page: 1
        });
      } catch (e) {
        console.error(e)
        wx.showToast({ title:  (e && e.data && e.data.msg) || '加载失败', icon: 'none' });
        this.setData({ loading: false });
      }
    },
    // 跳转到记账页面
    onWriteTap() {
      wx.showActionSheet({
        itemList: ['支出', '收入'],
        success: res => {
          if (res.tapIndex === 0) {
            wx.navigateTo({ url: '/pages/finance/write/write?type=expense' });
          } else if (res.tapIndex === 1) {
            wx.navigateTo({ url: '/pages/finance/write/write?type=income' });
          }
        }
      });
    },
    goTask() {
      wx.navigateTo({ url: '/pages/finance/bill/bill' });
    },
    // 跳转到统计页面
    goStatistics(e) {
      // 根据点击的按钮决定跳转页面
      const dataset = e.currentTarget.dataset;
      if (dataset && dataset.type === 'search') {
        wx.navigateTo({ url: '/pages/finance/search/search' });
      } else {
        wx.navigateTo({ url: '/pages/finance/statistics/statistics' });
      }
    },
    // 跳转到设置页面
    goSetting() {
      wx.navigateTo({ url: '/pages/finance/setting/setting' });
    },
    goProfileCenter() {
      wx.navigateTo({ url: '/pages/finance/profile-center/profile-center' });
    },
    /**
     * 隐藏金额
     */
    toggleAmountVisibility() {
      this.setData({
        isAmountHidden: !this.data.isAmountHidden
      });
    },
    /**
     * 处理记录删除事件
     */
    onDeleteRecord(e) {
      // 重新加载记录列表
      this.loadRecords();
    },
    noop() {
      // 用于阻止事件冒泡，无实际逻辑
    }
  });